package com.syeet.gulimall.order.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.rabbitmq.client.Channel;
import com.syeet.common.utils.PageUtils;
import com.syeet.common.utils.Query;
import com.syeet.gulimall.order.dao.OrderItemDao;
import com.syeet.gulimall.order.entity.OrderItemEntity;
import com.syeet.gulimall.order.entity.OrderReturnReasonEntity;
import com.syeet.gulimall.order.service.OrderItemService;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.core.MessageProperties;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.util.Map;

//@RabbitListener(queues = {"hello-java-queue"})
@Service("orderItemService")
public class OrderItemServiceImpl extends ServiceImpl<OrderItemDao, OrderItemEntity> implements OrderItemService {

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<OrderItemEntity> page = this.page(
                new Query<OrderItemEntity>().getPage(params),
                new QueryWrapper<OrderItemEntity>()
        );

        return new PageUtils(page);
    }

    /**
     * queues：声明需要监听的队列
     * channel：当前传输数据的通道
     */
    //@RabbitHandler
    public void revieveMessage(Message message,
                               OrderReturnReasonEntity content,
                               Channel channel) {
        //拿到主体内容
        byte[] body = message.getBody();
        //拿到的消息头属性信息
        MessageProperties messageProperties = message.getMessageProperties();
        System.out.println("接受到的消息...内容" + message + "===内容：" + content);
        //channel内按顺序自增
        long deliveryTag = message.getMessageProperties().getDeliveryTag();
        System.out.println("deliveryTag值="+deliveryTag);
        //签收消息，非批量模式 multiple
        try {
            if(deliveryTag%2==0){
                channel.basicAck(deliveryTag,false);
                System.out.println("签收了消息="+deliveryTag);
            }else {
                /**
                 * 拒签消息
                 *   requeue=false 拒签消息后，将消息丢弃
                 *   requeue=true 发回服务器，重新入队列（避免无限入列，引入消费者失败重试机制）
                 */
                channel.basicNack(deliveryTag,false,true);
                System.out.println("没签收了消息="+deliveryTag);
            }

        } catch (IOException e) {
            //网络中断
            e.printStackTrace();
        }

    }

}